package com.mju.exception;

import java.io.IOException;

import org.json.JSONObject;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.mju.utils.RespData;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler,AuthenticationEntryPoint {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {

		this.output(403,"未授权，禁止访问",request,response);		
	}
	
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {

		this.output(401,"未认证，禁止访问",request,response);		
	}
	
	private void output(int code,String msg,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=utf-8");
	
		RespData respData=RespData.failed(msg, code);
		
		JSONObject json=(JSONObject) JSONObject.wrap(respData);
		log.error(json.toString());
		response.getWriter().write(json.toString());
	}

}
